import { defineStore } from 'pinia';
import cartApi from '/shop/api/cart';
import { ref } from 'vue';
const cart = defineStore(
	'cart',
	() => {
		let list = ref([]);
		let selectedIds = ref([]);
		let isAllSelected = ref(false);
		let cartSelectedTotalPrice = ref('0.00');

		let totalPriceSelected = () => {
			let price = 0;
			if (!selectedIds.value.length) return price.toFixed(2);
			list.value.forEach((item) => {
				price += selectedIds.value.includes(item.id)
					? Number(item.price) * item.quantity
					: 0;
			});
			return price.toFixed(2);
		};

		let getList = async () => {
			const { data, code } = await cartApi.list({});
			if (code === '0') {
				list.value = data;
				console.log('list.value: ', list.value.length);
				if (list.value.length === 0 || selectedIds.value.length === 0) {
					isAllSelected.value = false;
				} else {
					isAllSelected.value = selectedIds.value.length === list.value.length;
				}
			}
		};

		let add = async (goodsInfo) => {
			console.log('goodsInfo: ', goodsInfo);
			const { code } = await cartApi.create({
				goodsId: goodsInfo.goodsId,
				quantity: goodsInfo.quantity || 1,
				goodsSpecValues: goodsInfo.goodsSpecValues,
			});
			if (code === '0') {
				getList();
			}
		};

		let update = async (cartInfo) => {
			console.log('cart  update: ', cartInfo);
			const { code } = await cartApi.update({
				id: cartInfo.id,
				goodsId: cartInfo.goodsId,
				quantity: cartInfo.quantity || 1,
				goodsSpecValues: cartInfo.goodsSpecValues,
			});
			if (code === '0') {
				getList();
				isAllSelected.value = selectedIds.value.length === list.value.length;
			}
		};

		let deleted = async (ids) => {
			if (typeof ids === 'array') {
				ids = ids.join(',');
			}
			const { code } = await cartApi.delete(ids);
			if (code === '0') {
				selectAll(false);
				getList();
			}
		};

		// 选中购物车商品
		let selectSingle = (goodsId) => {
			if (!selectedIds.value.includes(goodsId)) {
				selectedIds.value.push(goodsId);
			} else {
				selectedIds.value.splice(selectedIds.value.indexOf(goodsId), 1);
			}
			isAllSelected.value = selectedIds.value.length === list.value.length;
		};

		let selectAll = (flag) => {
			isAllSelected.value = flag;
			selectedIds.value = [];
			if (flag) {
				list.value.forEach((item) => {
					selectedIds.value.push(item.id);
				});
			}
		};

		let emptyList = () => {
			list.value = [];
			selectedIds.value = [];
			isAllSelected.value = false;
			cartSelectedTotalPrice.value = '0.00';
		};

		let submitUpdateList = () => {
			console.log('更新提交订单的购物车商品....: ', selectedIds.value);
			deleted(selectedIds.value);
		};

		return {
			list,
			selectedIds,
			isAllSelected,
			cartSelectedTotalPrice,
			totalPriceSelected,
			emptyList,
			selectAll,
			selectSingle,
			deleted,
			update,
			add,
			getList,
			submitUpdateList,
		};
	},
	{
		persist: {
			enabled: true,
		},
	},
);

export default cart;
